package tech.yunland.shop.web;

import com.alibaba.fastjson.JSON;
import com.moyuer.bsf.common.Pagination;
import com.moyuer.bsf.web.controller.BaseController;
import org.activiti.engine.IdentityService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import tech.yunland.activity.domain.imodel.BaseModel;
import tech.yunland.activity.domain.services.IWorkflowService;
import tech.yunland.shop.domain.model.PurchaseBill;
import tech.yunland.shop.domain.model.PurchaseBillEntry;
import tech.yunland.shop.domain.service.PurchaseBillService;

import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

/**
 * 采购单控制器
 *
 * @author 文卡<wkwenka@gmail.com>  on 17-2-13.
 */
@RestController
@RequestMapping("/purchase_bill")
public class PurchaseBillController extends BaseController {

    @Autowired
    private PurchaseBillService purchaseBillService;


    @Autowired
    private IdentityService identityService;
    @Autowired
    private IWorkflowService<BaseModel> workflowService;

    @Value("${processdefId}")
    private String processdefId;

    /**
     * 保存采购单
     *
     * @param purchaseBill
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public void savePurchaseBill(@RequestBody PurchaseBill purchaseBill) throws UnsupportedEncodingException {
        // 输出日志
        logger.info(JSON.toJSONString(purchaseBill, true));

        //判断组织
        if (purchaseBill.getOrgan() == null) {
            purchaseBill.setOrgan(primaryOrgan);
        }

        //判断创建人
        if (purchaseBill.getCreator() == null) {
            purchaseBill.setCreator(currentUser);
        }

        if (purchaseBill.getEntries() == null || purchaseBill.getEntries().size() == 0) {
            throw new RuntimeException("商品信息参数错误，没有商品。");
        }

        purchaseBill.setProcessdefId(processdefId);
        purchaseBillService.savePurchase(purchaseBill);

        saveLog("采购单：[" + purchaseBill.getSn() + "] 保存成功！");
    }

    /**
     * 采购单生效
     *
     * @param id
     */
    @RequestMapping(value = "/pay/{id}", method = RequestMethod.POST)
    public void updatePurchaseBill(@PathVariable("id") String id) {
        purchaseBillService.updatePurchaseBill(id);
    }

    /**
     * 删除采购单
     *
     * @param id
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public void deletePurchaseBill(@PathVariable("id") String id) {
        purchaseBillService.deletePurchaseBill(id);
    }

    /**
     * 查询所有采购单
     *
     * @param param
     * @param biztype 采购单类型 0：待采购  1：已采购
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public Pagination<HashMap<String, Object>> getAllPurchaseBill(
            @RequestParam(required = false) String param,
            @RequestParam(required = false) Integer biztype,
            @RequestParam(required = false) List<Integer> states,
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer rows) {
        Pagination result = new Pagination(page, rows);
        Integer startIdx = result.getStartIdx();
        Integer count = purchaseBillService.getAllBillSize(param, primaryOrganId, biztype, states);
        List<PurchaseBill> records = purchaseBillService.getAllBill(param, primaryOrganId, biztype, states, startIdx, rows);
        result.setCount(count);
        result.setRecords(records);

        return result;

    }

    /**
     * 根据主键获取采购单
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/purchase/{id}", method = RequestMethod.GET)
    public PurchaseBill getPurchasesById(@PathVariable String id) {
        return purchaseBillService.getPurchaseBillById(id);
    }

    /**
     * 保存分录
     *
     * @param billEntries
     */
    @RequestMapping(value = "/saveEntry", method = RequestMethod.POST)
    public void saveEntry(@RequestBody @Valid PurchaseBillEntry... billEntries) {

        for (PurchaseBillEntry billEntry : billEntries
                ) {
            purchaseBillService.savePurchaseEntry(billEntry);
        }
    }

    /**
     * 查询指定出采购单的所有分录
     *
     * @Return List<SaleBill>
     */
    @RequestMapping(value = "/purchaseEntry", method = RequestMethod.GET)
    public Pagination getPurchaseBillEntry(
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer rows,
            @RequestParam String ownerId) {
        Pagination pagination = new Pagination<>(page, rows);
        Integer startIdx = pagination.getStartIdx();
        pagination.setCount(purchaseBillService.getBillEntrySize(ownerId));
        pagination.setRecords(purchaseBillService.getBillEntry(ownerId, startIdx, rows));
        return pagination;
    }

    /**
     * 查询指定采购单 不分页
     * @param ownerId
     * @return
     */
    @RequestMapping(value = "/purchaseEntry/list", method = RequestMethod.GET)
    public List getPurchaseBillEntryList(@RequestParam String ownerId) {
        List<PurchaseBillEntry> billEntry = purchaseBillService.getBillEntry(ownerId, Integer.valueOf(-1), Integer.valueOf(-1));
        return billEntry;
    }

    /**
     * 根据主键查看当前分录详细信息
     *
     * @param id 分录主键
     * @return
     */
    @RequestMapping(value = "/purchaseBillEntry/{id}", method = RequestMethod.GET)
    public PurchaseBillEntry getPurcahseBillEntryInfo(@PathVariable String id) {
        return purchaseBillService.getPurcahseBillEntryInfo(id);
    }

    /**
     * 修改分录
     *
     * @param purchaseBillEntry
     */
    @RequestMapping(value = "/updateEntry", method = RequestMethod.POST)
    public void updatePurchaseEntry(@RequestBody PurchaseBillEntry purchaseBillEntry) {
        purchaseBillService.updatePurchaseEntry(purchaseBillEntry);
    }

    /**
     * 根据主键删除分录
     */
    @RequestMapping(value = "/purchase/{id}", method = RequestMethod.DELETE)
    public void deletePurchaseBillEntry(@PathVariable String id) {
        purchaseBillService.deletePurchaseBillEntry(id);
    }

    /**
     * 启动采购单审批流程
     *
     * @param billId
     */
    @RequestMapping(value = "/runTime", method = RequestMethod.GET)
    public void purchaseBillRunTime(@RequestParam(required = false) String billId) {

        this.identityService.setAuthenticatedUserId(this.currentUser.getId());

        PurchaseBill purchaseBillById = purchaseBillService.getPurchaseBillById(billId);

        if (purchaseBillById == null) {
            throw new RuntimeException("该单据异常");
        }

        String processdefId = purchaseBillById.getProcessdefId(); //流程ID

        if (StringUtils.isBlank(processdefId)) {
            throw new RuntimeException("该单据没有绑定流程");
        }

        if (purchaseBillById.getState().intValue() == 0) {
            HashMap<String, Object> creatUser = new HashMap<>();
            creatUser.put("creatUser", this.currentUser.getName());

            workflowService.startProcessByPrcessdefId(processdefId, billId, creatUser, this.currentUserId);

            //将单据设置为审核中。
            purchaseBillService.updateState(billId, 1);

            saveLog("采购单：[" + purchaseBillById.getSn() + "] 开始审批！");
        } else {
            throw new RuntimeException("该单据不能审批");
        }

    }

    /**
     * 修改单据备注
     *
     * @param bill
     */
    @RequestMapping(value = "/updateRemark/", method = RequestMethod.POST)
    public void updateBillRemark(@RequestBody PurchaseBill bill) {
        purchaseBillService.updateRemark(bill.getId(), bill.getRemark());
    }

    @RequestMapping(value = "/updateBill",method = RequestMethod.POST)
    public void updateBill(@RequestBody PurchaseBill purchaseBill){
        this.purchaseBillService.updateBill(purchaseBill);
    }
}
